package cn.com.self.apis.util;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * @Description 将Date、Integer、Double数据绑定到实体（与@DateTimeFormat同时存在时，此方法生效）
 *
 * @date 2019-03-17
 */
public class AbstractDateConvertController {
    @InitBinder//@InitBinder:springMVC在绑定表单之前注册以下编辑器
    public void init(WebDataBinder binder) {
        //注册Date编辑器
        binder.registerCustomEditor(Date.class, new MyDateEditor());
        //注册Double编辑器
//        binder.registerCustomEditor(Double.class,new DoubleEditor());
        //注册Integer编辑器
//        binder.registerCustomEditor(Integer.class,new IntegerEditor());
    }

    private class MyDateEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            text = "null".equals(text) ? "" : text;
            if (StringUtils.isNotBlank(text)) {
                Date date = DateFormatUtil.parseDate(text);
                if (date == null) {
                    AssertUtil.throwException("无法将字符串[" + text + "]转换成日期格式！");
                }
                setValue(date);
            }
        }
    }

    public class DoubleEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (text == null || text.equals("")) {
                text = "0";
            }
            setValue(Double.parseDouble(text));
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }

    public class IntegerEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (text == null || text.equals("")) {
                text = "0";
            }
            setValue(Double.parseDouble(text));
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }
}
